﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Util.Extension;
using Microsoft.AspNetCore.Hosting;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Mvc.Rendering;
using AntUnion.FrameWork.Web.Extend;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class RebateLevelController : BaseController
    {
        private readonly mtContext _context;

        public RebateLevelController(mtContext context, IWebHostEnvironment env) : base(context, env)
        {
            _context = context;
        }

        #region 列表
        public IActionResult Index(int schemeId)
        {
            ViewBag.schemeId = schemeId;
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int schemeId)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.RebateLevels.Where(k => k.SchemeId == schemeId)
                           select new
                           {
                               id = y.Id,
                               pid = y.Pid,
                               names = y.Names,
                               cardinal = y.Cardinal == null ? "" : ((decimal)y.Cardinal).ToString("#,##0.0000"),
                               remark = y.Remark,
                               creator = y.Creator,
                               createDate = y.CreateDate,
                               sort = y.Sort,
                               state = y.State
                           };

                res.Code = 0;
                res.Count = data.Count();
                res.Data = await data.OrderBy(k => k.sort).ToListAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 获取品种
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetSymbols()
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.Symbols
                           select new
                           {
                               id = y.Symbol1,
                               text = y.Symbol1
                           };
                res.Code = 0;
                res.Count = data.Count();
                res.Data = await data.OrderBy(k => k.id).ToListAsync();
                ;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加等级
        /// <summary>
        /// 添加等级
        /// </summary>
        /// <param name="schemeId"></param>
        /// <returns></returns>
        public IActionResult CreateLevel(int schemeId)
        {
            int Sort = 1;
            if (_context.RebateLevels.Where(k => k.SchemeId == schemeId && k.Pid == 0).Count() > 0)
            {
                Sort = _context.RebateLevels.Where(k => k.SchemeId == schemeId && k.Pid == 0).Max(k => k.Sort) + 1;
            }
            ViewBag.schemeId = schemeId;
            ViewBag.Sort = Sort;
            return View();
        }

        /// <summary>
        /// 添加等级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> CreateLevel(RebateLevel model)
        {
            Result res = new Result();
            try
            {
                if (!ToLevelExists(model.Level, model.SchemeId))
                {
                    model.Pid = 0;
                    model.Creator = User.LoginName;
                    model.CreateDate = DateTime.Now;
                    model.State = 1;
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Data = "addTermExist";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = "submitFail";
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑等级
        public async Task<IActionResult> EditLevel(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            RebateLevel data = await _context.RebateLevels.FindAsync(id);
            if (data == null)
            {
                return NotFound();
            }
            return View(data);
        }
        /// <summary>
        /// 编辑等级
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditLevel(RebateLevel item)
        {
            Result res = new Result();
            try
            {
                if (!ToLevelExists(item.Level, item.SchemeId, item.Id))
                {
                    RebateLevel model = await _context.RebateLevels.FindAsync(item.Id);
                    if (model != null)
                    {
                        model.Level = item.Level;
                        model.Names = item.Names;
                        model.Sort = item.Sort;
                        model.Remark = item.Remark;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Data = "editTermNotExist";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Data = "addTermExist";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = "submitFail";
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加品种与返佣基数
        /// <summary>
        /// 添加品种与返佣基数
        /// </summary>
        /// <param name="schemeId"></param>
        /// <returns></returns>
        public IActionResult Create(int schemeId, int pid)
        {
            int Sort = 1;
            if (_context.RebateLevels.Where(k => k.SchemeId == schemeId && k.Pid == pid).Count() > 0)
            {
                Sort = _context.RebateLevels.Where(k => k.SchemeId == schemeId && k.Pid == pid).Max(k => k.Sort) + 1;
            }
            ViewBag.Sort = Sort;
            ViewBag.Pid = pid;
            ViewBag.SchemeId = schemeId;
            return View();
        }

        /// <summary>
        /// 添加品种与返佣基数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(RebateLevel model)
        {
            Result res = new Result();
            try
            {
                RebateLevel rebateLevel = _context.RebateLevels.FirstOrDefault(k => k.Id == model.Pid);
                if (!ToExists(model.Names, model.SchemeId, rebateLevel.Level))
                {
                    if (rebateLevel != null)
                    {
                        model.Creator = User.LoginName;
                        model.CreateDate = DateTime.Now;
                        model.State = 1;
                        model.Level = rebateLevel.Level;
                        _context.Add(model);
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Data = "selectRebateLevel";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Data = "addTermExist";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = "submitFail";
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑品种与返佣基数
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            RebateLevel data = await _context.RebateLevels.FindAsync(id);
            if (data == null)
            {
                return NotFound();
            }
            return View(data);
        }
        /// <summary>
        /// 编辑品种与返佣基数
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(RebateLevel item)
        {
            Result res = new Result();
            try
            {
                RebateLevel rebateLevel = await _context.RebateLevels.FindAsync(item.Pid);
                if (!ToExists(item.Names, item.SchemeId, rebateLevel.Level, item.Id))
                {
                    RebateLevel model = await _context.RebateLevels.FindAsync(item.Id);
                    if (model != null)
                    {
                        if (rebateLevel != null)
                        {
                            model.Cardinal = item.Cardinal;
                            model.Names = item.Names;
                            model.Level = rebateLevel.Level;
                            model.Sort = item.Sort;
                            model.Remark = item.Remark;
                            res.Code = 0;
                            res.Data = await _context.SaveChangesAsync();
                        }
                        else
                        {
                            res.Code = 1;
                            res.Data = "selectRebateLevel";
                        }
                    }
                    else
                    {
                        res.Code = 1;
                        res.Data = "editTermNotExist";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Data = "addTermExist";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = "submitFail";
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateState(int id, int intState)
        {
            ListResult res = new ListResult();
            try
            {
                RebateLevel data = await _context.RebateLevels.FindAsync(id);
                data.State = (ulong)intState;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            Result res = new Result();
            try
            {
                RebateLevel data = await _context.RebateLevels.FindAsync(id);
                if (data.Pid == 0 && _context.RebateLevels.Any(k => k.Pid == data.Id))
                {
                    res.Code = 1;
                    res.Msg = "levelNotAllowDel";
                    return new JsonResult(res);
                }
                _context.RebateLevels.Remove(data);
                res.Code = 0;
                res.Msg = "deleteSuccess";
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.ToString();
                res.Msg = "deleteFail";
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断等级是否存在
        /// </summary>
        /// <param name="level">等级</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool ToLevelExists(int? level, int schemeId, int id = 0)
        {
            if (id == 0)
                return _context.RebateLevels.Any(e => e.Level == level && e.SchemeId == schemeId);
            else
                return _context.RebateLevels.Any(e => e.Id != id && e.SchemeId == schemeId && e.Level == level);
        }

        /// <summary>
        /// 判断品种是否存在
        /// </summary>
        /// <param name="Name">名称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool ToExists(string Name, int schemeId, int? level, int id = 0)
        {
            if (id == 0)
                return _context.RebateLevels.Any(e => e.Names == Name && e.SchemeId == schemeId && e.Level == level);
            else
                return _context.RebateLevels.Any(e => e.Id != id && e.SchemeId == schemeId && e.Level == level && e.Names == Name);
        }
        #endregion
    }
}
